<?php
declare (strict_types = 1);

namespace app\index\controller;
use think\facade\Db;
use think\facade\View;

use app\common\model\JSSDK as JSSDKModel;
use app\common\model\Users as UsersModel;

class Wechat  extends Base
{

    private $app_id = 'wxe5d55d481983958e';
    private $app_secret = 'def0acf61910502d9e3f0104c0eee4bf';

    //微信开发平台 网站应用(微信二维码扫码登录)
    private $h5_app_id = 'wx0552fd79288102c0';
    private $h5_app_secret = 'a088e93d1d1909414fe7d2b2c2620272';

    /**
     * 获取微信配置文件
     */
    public function get_weinxin_params(){
//        $dyurl = I('dyurl/s','');
        $host = 'https://'.$_SERVER['HTTP_HOST'];
        $data['appid'] = 'wxe5d55d481983958e';
//        ,array('dyurl'=>$dyurl)
        $data['return_url'] = $host.url('index/Wechat/wechatlogin'); //扫码回调地址
        $data['site_url'] = $host;
        $this->ajaxReturn(['errcode'=>1,'message'=>'请求成功','data'=>$data]);
    }
    /**
     * 打开微信扫码登录地址
     * @author ph
     */
    public function wechatlogin(){
        //$dyurl = I('dyurl/s','');
        if(!isset($_GET['code'])){
            $domain = request()->domain();
            $return_url = $domain.'/index/wechat/wechatlogin'; //扫码回调地址
            $url = "https://open.weixin.qq.com/connect/qrconnect?appid={$this->h5_app_id}&redirect_uri=".urlencode($return_url)."&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
            header('location:'.$url);
            exit;
        }else{
            /*微信扫码回调*/
            $wxuser = $this->GetOpenid(); //授权获取openid以及微信用户信息

            $UsersModel = new UsersModel();
            $user_one = $UsersModel->where('unionid','=',$wxuser['unionid'])->find();

            $wxuser_json = json_encode($user_one);
            if($user_one['id']){
                if($user_one['mobile'] == ''){
                    $this->redirect(request()->domain().'/users/bind_phone?unionid='.$wxuser['unionid']);
                }
            }else{
                $this->redirect(request()->domain().'/users/bind_phone?unionid='.$wxuser['unionid']);
            }

            $res = $UsersModel -> thirdLogin($wxuser);
            if($res['code'] == 1){
                $this->redirect(request()->domain().'/index/index');
            }else{
                $this->redirect(request()->domain().'/index/index');
            }
        }
    }


    public function GetOpenid(){
        if($_GET['code']){
            //上面获取到code后这里跳转回来
            $code = $_GET['code'];
            $data = $this->getOpenidFromMp($code);//获取网页授权access_token和用户openid
            $data2 = $this->GetUserInfo($data['access_token'],$data['openid']);//获取微信用户信息
            /*去除微信名称中的表情*/
            $data['nickname'] = empty($data2['nickname']) ? '微信用户' : filterEmoji(trim($data2['nickname']));
            $data['head_pic'] = $data2['headimgurl'];
            $data['oauth_child'] = 'mp';
            $data['oauth'] = 'weixin';
//            $_SESSION['openid'] = $data['openid'];
            if(isset($data2['unionid'])){
                $data['unionid'] = $data2['unionid'];
            }
            return $data;
        }
    }


    public function GetOpenidFromMp($code)
    {
        //通过code获取网页授权access_token 和 openid 。网页授权access_token是一次性的，而基础支持的access_token的是有时间限制的：7200s。
        //1、微信网页授权是通过OAuth2.0机制实现的，在用户授权给公众号后，公众号可以获取到一个网页授权特有的接口调用凭证（网页授权access_token），通过网页授权access_token可以进行授权后接口调用，如获取用户基本信息；
        //2、其他微信接口，需要通过基础支持中的“获取access_token”接口来获取到的普通access_token调用。
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->h5_app_id}&secret={$this->h5_app_secret}&code={$code}&grant_type=authorization_code";

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);//设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch);//运行curl，结果以json形式返回
        $data = json_decode($res,true);
        curl_close($ch);
        return $data;
    }
    /**
     *
     * 通过access_token openid 从工作平台获取UserInfo
     * @return openid
     */
    public function GetUserInfo($access_token,$openid)
    {
        // 获取用户 信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);//设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch);//运行curl，结果以jason形式返回
        $data = json_decode($res,true);
        curl_close($ch);

        return $data;
    }

    /**
     * 获取微信授权链接(用于微信支付的授权)
     *
     * @param string $redirect_uri 跳转地址
     * @param mixed $state 参数
     */
    public function get_authorize_url($redirect_uri = '', $state = '')
    {
        $redirect_uri = urlencode($redirect_uri);
        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
        //return dyajaxReturn(1,'跳转',$url);
        $this ->redirect($url);
    }


    //获取jssdk config的值
    public function getSignPackage(){
        $JSSDKModel = new JSSDKModel();
        $data = $JSSDKModel -> getSignPackage();
        return dyajaxReturn(1,'获取成功',$data);
    }



}
